{% extends 'base.html' %}
{% load static %}

  {% block title %}
  <title>主机添加</title>
  {% endblock title %}

	{% block navheader %}
    <section class="content-header">
      <div class="container-fluid">
        <div class="row mb-1">
          <div class="col-12">
            <ol class="breadcrumb">
              <li class="breadcrumb-item">主机管理</li>
			  <li class="breadcrumb-item"><a href="{% url 'server:hosts' %}">主机</a></li>
			  <li class="breadcrumb-item active">主机添加</li>
            </ol>
          </div>
        </div>
      </div><!-- /.container-fluid -->
    </section>
	{% endblock navheader %}
	
		  {% block content %}
          <div class="card card-primary content-list">
            <div class="card-header">
              <h3 class="card-title">主机添加</h3>
				<div class="card-tools">
				  <!--button type="button" class="btn btn-tool" data-widget="collapse">
					<i class="fas fa-minus"></i>
				  </button>
				  <button type="button" class="btn btn-tool" data-widget="maximize">
				  <i class="fas fa-expand"></i>
                  </button>
				  <button type="button" class="btn btn-tool" data-widget="remove">
					<i class="fas fa-times"></i>
				  </button-->
				</div>
            </div>
            <!-- /.card-header -->
            <div class="card-body row">
				<div class="col-2 pt-1 pb-1">主机名<span style="color:red;"> * </span>：</div><div class="col-10 pt-1 pb-1"><input class="form-control" type="text" id="hostname" onkeyup="check_hostname();" onblur="check_hostname();"></div>
				<div class="offset-2 col-10 pb-1"><small id="hostname_error" style="color:red;"></small></div>
				
				<div class="col-2 pt-1 pb-1">类型：</div>
				<div class="col-10 pt-1 pb-1">
					<select class="form-control select2" id="type" style="width: 100%;">
						<option value="---" selected disabled>请选择类型</option>
						{% for type in type_choices %}
						<option value="{{ type.0 }}">{{ type.1 }}</option>
						{% endfor %}
					</select>
				</div>

				<div class="col-2 pt-1 pb-1">主机IP<span style="color:red;"> * </span>：</div><div class="col-10 pt-1 pb-1"><input class="form-control" type="text" id="ip" onkeyup="check_ip();" onblur="check_ip();"></div>
				<div class="offset-2 col-10 pb-1"><small id="ip_error" style="color:red;"></small></div>
				
				<div class="col-2 pt-1 pb-1">公网IP：</div><div class="col-10 pt-1 pb-1"><input class="form-control" type="text" id="wip" onkeyup="check_wip();" onblur="check_wip();"></div>
				<div class="offset-2 col-10 pb-1"><small id="wip_error" style="color:red;"></small></div>
				
				<div class="col-2 pt-1 pb-1">协议：</div>
				<div class="col-10 pt-1 pb-1">
					<select class="form-control select2" id="protocol" style="width: 100%;">
						<option value="---" selected disabled>请选择协议</option>
						{% for protocol in protocol_choices %}
						<option value="{{ protocol.0 }}">{{ protocol.1 }}</option>
						{% endfor %}
					</select>
				</div>
				<div class="col-2 pt-1 pb-1">环境：</div>
				<div class="col-10 pt-1 pb-1">
					<select class="form-control select2" id="env" style="width: 100%;">
					    <option value="---" selected disabled>请选择环境</option>
						{% for env in env_choices %}
						<option value="{{ env.0 }}">{{ env.1 }}</option>
						{% endfor %}
					</select>
				</div>
				<div class="col-2 pt-1 pb-1">端口<span style="color:red;"> * </span>：</div><div class="col-10 pt-1 pb-1"><input class="form-control" type="text" id="port" onkeyup="check_port();" onblur="check_port();"></div>
				<div class="offset-2 col-10 pb-1"><small id="port_error" style="color:red;"></small></div>
				
				<div class="col-2 pt-1 pb-1">平台：</div>
				<div class="col-10 pt-1 pb-1">
					<select class="form-control select2" id="platform" style="width: 100%;">
						<option value="---" selected disabled>请选择台</option>
						{% for platform in platform_choices %}
						<option value="{{ platform.0 }}">{{ platform.1 }}</option>
						{% endfor %}
					</select>
				</div>
				
				<div class="col-2 pt-1 pb-1">系统/型号<span style="color:red;"> * </span>：</div><div class="col-10 pt-1"><input class="form-control" type="text" id="release" onkeyup="check_release();" onblur="check_release();"></div>
				<div class="offset-2 col-10 pb-1"><small id="release_error" style="color:red;"></small></div>
				
				<div class="col-2 pt-1 pb-1">远程用户：</div>
				<div class="col-10 pt-1 pb-1">
					<select class="form-control select2" id="binduserid" style="width: 100%;">
						<option value="---" selected disabled>请选择用户</option>
						{% for user in all_users %}
						<option value="{{ user.id }}">{{ user.name }}</option>
						{% endfor %}
					</select>
				</div>
				<div class="col-2 pt-1 pb-1">备注：</div><div class="col-10 pt-1 pb-1"><textarea id="memo" class="form-control"></textarea></div>
				<div class="offset-2 col-10 pt-1 pb-1">
					<div class="custom-switch custom-switch-on-success">
                      <input type="checkbox" class="custom-control-input" id="enabled" checked>
                      <label class="custom-control-label" for="enabled">启用</label>
                    </div>
				</div>
				<div class="offset-2 col-10 pt-2"><a class="btn btn-default" href="{% url 'server:hosts' %}">返回</a> <button class="btn btn-success ml-2" onclick="changeuserprofile(this);">提交</button><span id="feed_error" class="ml-2" style="color:red;"></span></div>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card --> 
		  {% endblock content %}

{% block js %}
<!-- DataTables -->
<script src="{% static 'adminlte/plugins/datatables/jquery.dataTables.js' %}"></script>
<script src="{% static 'adminlte/plugins/datatables/dataTables.bootstrap4.js' %}"></script>
<script>
	$("#datatables-lists").DataTable({
		language: {
			"sProcessing": "处理中...",
			"sLengthMenu": "显示 _MENU_ 项结果",
			"sZeroRecords": "没有匹配结果",
			"sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
			"sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
			"sInfoFiltered": "(由 _MAX_ 项结果过滤)",
			"sInfoPostFix": "",
			"sSearch": "搜索:",
			"sUrl": "",
			"sEmptyTable": "表中数据为空",
			"sLoadingRecords": "载入中...",
			"sInfoThousands": ",",
			"oPaginate": {
				"sFirst": "首页",
				"sPrevious": "上页",
				"sNext": "下页",
				"sLast": "末页"
			},
			"oAria": {
				"sSortAscending": ": 以升序排列此列",
				"sSortDescending": ": 以降序排列此列"
			}
		},
		destroy: true,	// 允许重建
		bProcessing:true,  // 表格数据过多处理时显示: sProcessing
		lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "全部"]],
		order: [],
		 //scrollY: 480,	// 滚动条
		 //scrollCollapse: true,
		 //jQueryUI: true,
		 stateSave: true,	// 保存最后一次分页信息、排序信息，当页面刷新，或者重新进入这个页面，恢复上次的状态。
		 stateDuration: 86400,	// 本地储存(0~更大)还是session储存(-1) 
	});

	// 校验表单数据
	check_hostname = function() {
		var hostname = $('#hostname').val();
		if (hostname == '') {
			$('#hostname').removeClass("is-valid");
			$('#hostname').addClass("is-invalid");
			$('#hostname_error').text('主机名不能未空');
			return false;
		//} else if(/[^0-9a-zA-Z\.@\-\_]+/g.test(hostname)) {	// 正则判断
		//	$('#hostname').removeClass("is-valid");
		//	$('#hostname').addClass("is-invalid");
		//	$('#hostname_error').text('主机名必须为数字、字母、 @、 -、 _ 或者 .');
		//	return false;
		} else {
			$('#hostname').removeClass("is-invalid");
			$('#hostname').addClass("is-valid");
			$('#hostname_error').text('');
			return true;
		};
	}
	
	check_ip = function() {		// 只支持IPV4
		var ip = $('#ip').val();
		if (ip == '') {
			$('#ip').removeClass("is-valid");
			$('#ip').addClass("is-invalid");
			$('#ip_error').text('主机IP不能未空');
			return false;
		} else if(!/^((1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([1-9]\.))((1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([0-9]\.)){2}((1[0-9][0-9])|(2[0-4][0-9])|(25[0-5])|([1-9][0-9])|([1-9]))$/.test(ip)) {	// 正则判断
			$('#ip').removeClass("is-valid");
			$('#ip').addClass("is-invalid");
			$('#ip_error').text('主机IP格式不正确');
			return false;
		} else {
			$('#ip').removeClass("is-invalid");
			$('#ip').addClass("is-valid");
			$('#ip_error').text('');
			return true;
		};
	}
	
	check_wip = function() {
		var wip = $('#wip').val();
		if (wip == '') {
			$('#wip').removeClass("is-invalid");
			$('#wip').removeClass("is-valid");
			//$('#wip').addClass("is-valid");
			$('#wip_error').text('');
			return true;
		} else if(!/^((1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([1-9]\.))((1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([0-9]\.)){2}((1[0-9][0-9])|(2[0-4][0-9])|(25[0-5])|([1-9][0-9])|([1-9]))$/.test(wip)) {
			$('#wip').removeClass("is-valid");
			$('#wip').addClass("is-invalid");
			$('#wip_error').text('公网IP格式不正确');
			return false;
		} else {
			$('#wip').removeClass("is-invalid");
			$('#wip').addClass("is-valid");
			$('#wip_error').text('');
			return true;
		};
	}

	check_port = function() {		// 只支持IPV4
		var port = $('#port').val();
		if (port == '') {
			$('#port').removeClass("is-valid");
			$('#port').addClass("is-invalid");
			$('#port_error').text('端口不能未空');
			return false;
		} else if(!/^(([1-9])|([1-9][0-9])|([1-9][0-9]{2})|([1-9][0-9]{3})|([1-5][0-9]{4})|(6[0-4][0-9]{3})|(65[0-4][0-9]{2})|(655[0-2][0-9])|(6553[0-5]))$/.test(port)) {	// 正则判断 1-65535
			$('#port').removeClass("is-valid");
			$('#port').addClass("is-invalid");
			$('#port_error').text('端口范围必须为 1-65535 不正确');
			return false;
		} else {
			$('#port').removeClass("is-invalid");
			$('#port').addClass("is-valid");
			$('#port_error').text('');
			return true;
		};
	}
	
	check_release = function() {
		var release = $('#release').val();
		if (release == '') {
			$('#release').removeClass("is-valid");
			$('#release').addClass("is-invalid");
			$('#release_error').text('系统/型号不能未空');
			return false;
		} else if(/[@#\$%\^&\*]+/g.test(release)) {	// 正则判断
			$('#release').removeClass("is-valid");
			$('#release').addClass("is-invalid");
			$('#release_error').text('系统/型号不能存在特殊符号');
			return false;
		} else {
			$('#release').removeClass("is-invalid");
			$('#release').addClass("is-valid");
			$('#release_error').text('');
			return true;
		};
	}
	
	// 校验表单数据

	// 添加主机
	changeuserprofile = function(event) {
		toastr.options.closeButton = true;
		toastr.options.showMethod = 'slideDown';
		toastr.options.hideMethod = 'fadeOut';
		toastr.options.closeMethod = 'fadeOut';
		toastr.options.timeOut = 3000;
		toastr.options.extendedTimeOut = 0;	
		toastr.options.progressBar = true;
		toastr.options.positionClass = 'toast-top-right'; 
		
		$(event).removeAttr("onclick");
		$(event).attr("disabled", true);

		var check_right = new Array();

		var hostname = $('#hostname').val();
		check_right[0] = check_hostname();
		
		var type = $('#type').val();
		
		var ip = $('#ip').val();
		check_right[1] = check_ip();
		
		var wip = $('#wip').val();
		check_right[2] = check_wip();
		
		var protocol = $('#protocol').val();
		var env = $('#env').val();
		var platform = $('#platform').val();
		
		var port = $('#port').val();
		check_right[3] = check_port();
		
		var release = $('#release').val();
		check_right[4] = check_release();
		
		var memo = $('#memo').val();
		var binduserid = $('#binduserid').val();
		var enabled;
		if ($("#enabled").is(':checked')) {
			enabled = true;
		} else {
			enabled = false;
		}
		
		csrfmiddlewaretoken = '{{ request.COOKIES.csrftoken }}';
		
		if (!/false/.test(check_right)) {
			$('#feed_error').text('');
			$.ajax({
				url: "{% url 'server_api:host_add' %}",
				async: true,
				type: 'POST',
				dataType: 'json',
				data: {
					'csrfmiddlewaretoken': csrfmiddlewaretoken,
					'hostname': hostname,
					'type': type,
					'ip': ip,
					'wip': wip,
					'protocol': protocol,
					'env': env,
					'platform': platform,
					'port': port,
					'release': release,
					'memo': memo,
					'enabled': enabled,
					'binduserid': binduserid,
				},
				timeout: 5000,
				cache: true,
				beforeSend: LoadFunction, //加载执行方法
				error: errFunction,  //错误执行方法
				success: succFunction, //成功执行方法
			});
		} else {
			$('#feed_error').text('信息填写有误，请检查并重新填写');
			$(event).removeAttr("disabled");
			$(event).attr("onclick", "changeuserprofile(this);");
			return false;
		};
		
		function LoadFunction() {
			// 提交中
		};
		
		function errFunction() {
			// 消息框
			toastr.error('添加主机错误');
			$(event).removeAttr("disabled");
			$(event).attr("onclick", "changeuserprofile(this);");
		};
		
		function succFunction(res) {
			if (res.code != 200) {
				// 消息框
				toastr.error('添加主机错误: ' + res.err);
				$(event).removeAttr("disabled");
				$(event).attr("onclick", "changeuserprofile(this);");
			} else {
				// 消息框
				toastr.options.timeOut = 1000;
				toastr.options.onHidden = function() { window.location.href = "{% url 'server:hosts' %}"; }
				toastr.success('添加主机成功');
			}
		};
	}
	// 添加主机
</script>

{% endblock js %}